package dk.hojlind.hackhunt.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;

import dk.hojlind.hackhunt.control.AdvisoryHandler;
import dk.hojlind.hackhunt.model.Advisory;

public class AdvisoryExploitDialog extends JDialog {

	//Public variables

	//Private variables
	AdvisoryHandler handler;
	List<String> answers;
	DefaultListModel<String> answerItems;
	Advisory advisory;

	public AdvisoryExploitDialog()
	{
		answers = new ArrayList<String>();
		answerItems = new DefaultListModel<String>();
		initUI();
	}

	public AdvisoryExploitDialog(AdvisoryHandler handler, Advisory advisory)
	{
		this.handler = handler;
		answers = new ArrayList<String>();
		answerItems = new DefaultListModel<String>();
		answers = getAnswers(advisory);

		answerItems.clear();
		for(int i = 0; i < answers.size(); i++)
		{
			answerItems.addElement(answers.get(i));
		}

		this.advisory = advisory;
		initUI();
	}

	private void initUI()
	{

		final JFrame frame = new JFrame();
		//Called to position components absolutely
		setLayout(null);

		//Set size and behavior of dialog
		setTitle("Give the correct answer to patch");
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setModalityType(ModalityType.APPLICATION_MODAL);
		setLocationRelativeTo(null);
		setSize(600, 400);

		//Create labels and textfields
		JLabel lblAnswers = new JLabel("Answers");
		lblAnswers.setBounds(20, 20, 240, 30);

		final JList<String> answerList = new JList<String>(answerItems);
		answerList.setBounds(20, 50, 300, 150);

		JButton accept = new JButton("Accept");
		accept.setBounds(160, 230, 100, 30);

		accept.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent event)
			{
				if(!(answerList.getSelectedIndex() < 0))
				{
					handler.sendAdvisoryAnswer(advisory.getID(), answerList.getSelectedIndex(), "exploit");
				}
			}
		});

		JButton cancel = new JButton("Cancel");
		cancel.setBounds(20, 230, 100, 30);

		cancel.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent event){
				dispose();
			}
		});


		//Add everything
		add(lblAnswers);
		add(answerList);
		add(accept);
		add(cancel);

	}

	private List<String> getAnswers(Advisory advisory) 
	{
		String[] answersArray = advisory.getChallenge().split("-br-");
		List<String> answersList = new ArrayList(Arrays.asList(answersArray));
		answersList.remove(0);		
		return answersList;
	}


}
